package com.ekuaitu.kuaitustaff.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.activity.CarTaskActivity;
import com.ekuaitu.kuaitustaff.adapter.SearchPositionAdapter;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.utils.CheckRegexUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Carson_Ho on 16/11/15.
 */
public class SearchPositionView extends LinearLayout implements TextWatcher, OnGetPoiSearchResultListener {

    private Context context;
    private List<String> tipsList = new ArrayList<>();
    /*UI组件*/
    private TextView cancelSearch;
    public EditText searchViewSearch;
    /*列表及其适配器*/
    private RecyclerView rcSearch;
    private SearchPositionAdapter searchAdapter;

    private FinishActivity mFinishActivity;
    private PoiSearch mPoiSearch = null;
    private List<String> name;

    /*三个构造函数*/
    //在构造函数里直接对搜索框进行初始化 - init()
    public SearchPositionView(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SearchPositionView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SearchPositionView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
    }


    /*初始化搜索框*/
    private void init() {
    /*    //实例化数据库SQLiteOpenHelper子类对象
        helper = new RecordSQLiteOpenHelper(context);*/
        //初始化UI组件
        initView();
        searchViewSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (CheckRegexUtils.checkParkName(searchViewSearch.getText().toString())) {
                        Intent intent = new Intent(context, CarTaskActivity.class);
                        intent.putExtra("searchParkName", searchViewSearch.getText().toString());
                        context.startActivity(intent);
                        mFinishActivity.finishActivity();
                        return false;
                    } else {
                        ToastUtils.makeText(context, "请填写停车场名称", ToastUtils.LENGTH_SHORT).show();
                        return true;
                    }
                }
                return false;
            }
        });
        searchViewSearch.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.toString().contains("%") || source.toString().contains("*")) {
                    return "";
                }
                return null;
            }
        }, new InputFilter.LengthFilter(40)});
    }


    /**
     * 封装的函数
     */

    /*初始化组件*/
    private void initView() {
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        LayoutInflater.from(context).inflate(R.layout.search_layout, this);
        searchViewSearch = (EditText) findViewById(R.id.searchView_search);
        searchViewSearch.addTextChangedListener(this);
        cancelSearch = (TextView) findViewById(R.id.cancel_search);
        rcSearch = (RecyclerView) findViewById(R.id.rc_search);
        //初始化recyclerView
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcSearch.setLayoutManager(linearLayoutManager);
        rcSearch.setItemAnimator(new DefaultItemAnimator());
        searchAdapter = new SearchPositionAdapter();
        rcSearch.setAdapter(searchAdapter);
        //点击取消结束Activity
        cancelSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(((Activity) context).getWindow().getDecorView().getWindowToken(), 0);
                mFinishActivity.finishActivity();
            }
        });
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(((Activity) context).getWindow().getDecorView().getWindowToken(), 0);

                Intent intent = new Intent(context, CarTaskActivity.class);
                intent.putExtra("searchParkName", name.get(position));
                context.startActivity(intent);
                mFinishActivity.finishActivity();
            }
        });

        //初始化直接以停车场为搜索关键字
        LatLng location = new LatLng(Double.parseDouble(((MyApplication) (MyApplication.getInstance())).getCurPosition()[0]), Double.parseDouble(((MyApplication) (MyApplication.getInstance())).getCurPosition()[1]));
        mPoiSearch.searchNearby(new PoiNearbySearchOption()
                .keyword("停车场")
                .sortType(PoiSortType.distance_from_near_to_far)
                .location(location)
                .radius(5000)
                .pageCapacity(10)
                .pageNum(0));

    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        LatLng location = new LatLng(Double.parseDouble(MyApplication.getInstance().getCurPosition()[0]), Double.parseDouble(MyApplication.getInstance().getCurPosition()[1]));
        mPoiSearch.searchNearby(new PoiNearbySearchOption()
                .keyword(searchViewSearch.getText().toString().trim())
                .sortType(PoiSortType.distance_from_near_to_far)
                .location(location)
                .radius(5000)
                .pageCapacity(10)
                .pageNum(0));

    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result != null && result.error == SearchResult.ERRORNO.NO_ERROR) {
            List<PoiInfo> poiInfos = result.getAllPoi();
            name = new ArrayList<>();
            for (int i = 0; i < poiInfos.size(); i++) {
                if (CheckRegexUtils.checkParkName(poiInfos.get(i).name)) {
                    name.add(poiInfos.get(i).name);
                }
            }
            searchAdapter.setNewData(name);
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }


    public interface FinishActivity {
        void finishActivity();
    }

    public void setFinishActivity(FinishActivity finishActivity) {
        mFinishActivity = finishActivity;
    }

    public void setSearchViewText(String content) {
        searchViewSearch.setText(content);
        searchViewSearch.setSelection(content.length());
    }


}

